package com.zhangpingyang.mybatisgenerator.service.impl;

import com.zhangpingyang.mybatisgenerator.common.api.CommonResult;
import com.zhangpingyang.mybatisgenerator.config.RedisService;
import com.zhangpingyang.mybatisgenerator.service.UmsMemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * @Author: Zhang Pingyang
 * @Date: 2019/11/8 15:52
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private RedisService redisService;
    @Value(value = "${redis.key.prefix.authCode}")
    private String AUTH_CODE;
    @Value(value = "${redis.key.expire.authCode}")
    private long expire;

    @Override
    public CommonResult generateAuthCode(String phone) {
        Assert.notNull(phone, "phone is null");
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        System.out.println(sb.toString());
        redisService.set(AUTH_CODE + phone, sb.toString(), expire);
        return null;
    }

    @Override
    public CommonResult verifyAuthCode(String phone, String authCode) {
        Assert.notNull(authCode, "phone is null");
        if (StringUtils.isEmpty(phone)) {
            return CommonResult.failed("请输入验证码");
        }
        String s = redisService.get(AUTH_CODE + phone);
        if (authCode.equals(s)) {
            return CommonResult.success(null, "验证码校验成功");
        } else {
            return CommonResult.failed("验证码不正确");
        }
    }
}
